console.log('jsonFormatter.js started loading');

window.JsonFormatter = function (rawJson, container) {
  console.log('JsonFormatter function called');

  const JsonViewer = () => {
    console.log('JsonViewer component rendering');
    const [isRawView, setIsRawView] = React.useState(false);
    const [formattedJson, setFormattedJson] = React.useState(null);

    React.useEffect(() => {
      try {
        const parsed = JSON.parse(rawJson);
        setFormattedJson(parsed);
        console.log('JSON parsed successfully');
      } catch (err) {
        console.error('Invalid JSON:', err);
      }
    }, [rawJson]);

    const renderJson = (obj, depth = 0) => {
      if (typeof obj !== 'object' || obj === null) {
        return <span className={`json-${typeof obj}`}>{JSON.stringify(obj)}</span>;
      }

      const isArray = Array.isArray(obj);
      const brackets = isArray ? ['[', ']'] : ['{', '}'];

      return (
        <div style={{ marginLeft: depth * 20 + 'px' }}>
          {brackets[0]}
          {Object.entries(obj).map(([key, value], index) => (
            <div key={key}>
              {!isArray && <span className="json-key">{`"${key}": `}</span>}
              {renderJson(value, depth + 1)}
              {index < Object.keys(obj).length - 1 && ','}
            </div>
          ))}
          {brackets[1]}
        </div>
      );
    };

    return (
      <div className="json-formatter">
        <div className="toolbar">
          <button onClick={() => setIsRawView(!isRawView)}>
            {isRawView ? 'Formatted' : 'Raw'}
          </button>
        </div>
        <pre className="json-content">
          {isRawView ? rawJson : renderJson(formattedJson)}
        </pre>
      </div>
    );
  };

  if (typeof React === 'undefined' || typeof ReactDOM === 'undefined') {
    console.error('React or ReactDOM is not defined');
    return;
  }

  try {
    ReactDOM.render(React.createElement(JsonViewer), container);
    console.log('React component rendered successfully');
  } catch (error) {
    console.error('Error rendering React component:', error);
  }
};

const loadScript = (src) => {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = src;
    script.onload = () => {
      console.log(`${src} loaded successfully`);
      resolve();
    };
    script.onerror = (error) => {
      console.error(`Error loading ${src}:`, error);
      reject(error);
    };
    document.head.appendChild(script);
  });
};

Promise.all([
  loadScript('https://unpkg.com/react@17/umd/react.production.min.js'),
  loadScript('https://unpkg.com/react-dom@17/umd/react-dom.production.min.js')
]).then(() => {
  console.log('React and ReactDOM loaded successfully');
}).catch((error) => {
  console.error('Failed to load React or ReactDOM:', error);
});

console.log('jsonFormatter.js finished loading');